/*
 * LPLTelescopeEventListenerImpl.java is part of htn-example.
 *
 * LPLTelescopeEventListenerImpl.java is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * LPLTelescopeEventListenerImpl.java is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LPLTelescopeEventListenerImpl.java.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.htn.telescopes.events;

import java.text.ParseException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import ngat.message.GUI_RCS.ReductionInfo;

import org.htn.repository.DocumentManager;
import org.htn.repository.DocumentManagerException;
import org.htn.telescope.TelescopeEventListener;
import org.htn.telescopes.rtml.parser.RTML31Create;
import org.htn.telescopes.rtml.parser.RTML31Parser;
import org.htn.telescopes.rtml.parser.RTMLCreate;
import org.htn.telescopes.rtml.parser.RTMLDocument;
import org.htn.telescopes.rtml.parser.RTMLException;
import org.htn.telescopes.rtml.parser.RTMLImageData;
import org.htn.telescopes.rtml.parser.RTMLObservation;
import org.htn.telescopes.rtml.parser.RTMLParser;


public class LPLTelescopeEventListenerImpl implements TelescopeEventListener,
		Runnable {

	/** Local reference to observation document manager */
	private DocumentManager<String> documentManager;

	/** A queue to share events between lower level telescope specific code */
	private BlockingQueue<ReductionInfo> eventqueue = new ArrayBlockingQueue<ReductionInfo>(
			100);

	public LPLTelescopeEventListenerImpl() {
		TelemetryReceiver telemetry_receiver = new TelemetryReceiver(this,
				"LPL_TEA");
	}

	public void listen() {

		/* Pull event message received from TCS off the queue */
		/* Eventqueue retrieves any available event messages timing out */
		/* after 10 seconds. */
		ReductionInfo eventmessage;
		try {
			eventmessage = eventqueue.poll(10, TimeUnit.SECONDS);

			/* Have we got a message */
			if (null != eventmessage) {
				/* Retrieve oid */
				String oid = eventmessage.getObsPathName();

				/* Get the rtml document corresponding to oid */
				String rtml = documentManager.query(oid);

				addRTMLImageLocation(eventmessage, rtml);

			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RTMLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (DocumentManagerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * @param eventmessage
	 * @param rtml
	 * @throws Exception 
	 */
	public String addRTMLImageLocation(ReductionInfo eventmessage, String rtml) throws Exception {
		/* Convert RTML string to RTML document. 
		 * Assumes only single observation */
		RTMLParser rtmlparser = new RTMLParser();
		rtmlparser.init(true);
		RTMLDocument rtmldocument = rtmlparser.parse(rtml);
		RTMLObservation observation = rtmldocument.getObservation(0);
		RTMLImageData imagedata = new RTMLImageData();
		// TODO: Add the correct path to create full URL
		imagedata.setImageDataURL(eventmessage.getFileName());
		observation.addImageData(imagedata);
		RTMLCreate newrtml = new RTMLCreate();
		newrtml.create(rtmldocument);
		return newrtml.toXMLString();
	}

	public void setDocumentManager(DocumentManager documentManager) {
		this.documentManager = documentManager;
	}

	public boolean addEventMessage(ReductionInfo eventmessage) {
		return eventqueue.add(eventmessage);
	}

	public void run() {

		listen();

	}

	public void handle(String id) {
		// TODO Auto-generated method stub
		
	}

}
